package cn.com.lyb.flink.window;

import cn.com.lyb.flink.bean.WaterSensor;
import cn.com.lyb.flink.split.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class WindowAggregateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env.socketTextStream("172.32.1.6", 1234).map(new WaterSensorMapFunction());

        KeyedStream<WaterSensor, String> keyBy = sensorDS.keyBy((KeySelector<WaterSensor, String>) waterSensor -> waterSensor.getId());

        WindowedStream<WaterSensor, String, TimeWindow> window = keyBy.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        // 增量聚合函数：来一条数据，计算一条数据； 窗口触发的时候输出计算结果
        /**
         * 窗口的aggregate
         * 1. 属于本窗口的第一条数据来，会创建窗口，创建累加器
         * 2. 增量聚合，来一条计算一条，调用一次add方法
         * 3. 窗口输出时调用一次getResult方法
         * 4. 输入，中间累加器，输出类型可以不一样，非常灵活
         */
        // AggregateFunction<IN, ACC, OUT>  IN输入类型，acc累加器类型，存储的中间计算结果的类型 out 输出类型
        SingleOutputStreamOperator<String> aggregate = window.aggregate(new AggregateFunction<WaterSensor, Integer, String>() {
            @Override
            public Integer createAccumulator() {
                System.out.println("创建累加器，初始化累加器");
                return 0;
            }

            @Override
            public Integer add(WaterSensor waterSensor, Integer integer) {
                System.out.println("调用add方法，聚合逻辑");
                return integer + waterSensor.getVc();
            }

            @Override
            public String getResult(Integer integer) {
                System.out.println("获取结果");
                return integer.toString();
            }

            @Override
            public Integer merge(Integer integer, Integer acc1) {
                System.out.println("调用merge方法，只有会话窗口才会用");
                return 0;
            }
        });
        aggregate.print();


        env.execute();
    }
}
